package com.haifeng.wdsh.gateway.exception;

import com.haifeng.wdsh.common.base.exception.BusinessException;
import com.haifeng.wdsh.common.base.exception.ErrorCode;
import com.haifeng.wdsh.common.base.exception.ErrorMsg;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.ResourceProperties;
import org.springframework.boot.autoconfigure.web.reactive.error.DefaultErrorWebExceptionHandler;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.cloud.gateway.support.NotFoundException;
import org.springframework.cloud.gateway.support.TimeoutException;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpStatus;
import org.springframework.web.reactive.function.server.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 异常处理类
 */
@Slf4j
public class ExceptionHandler extends DefaultErrorWebExceptionHandler {

    public ExceptionHandler(ErrorAttributes errorAttributes, ResourceProperties resourceProperties,
                            ErrorProperties errorProperties, ApplicationContext applicationContext) {
        super(errorAttributes, resourceProperties, errorProperties, applicationContext);
    }

    /**
     * 构建返回的JSON数据格式
     *
     * @param status  状态码
     * @param message 异常信息
     */
    public static Map<String, Object> response(int status, String message) {

        Map<String, Object> map = new HashMap<>(16);
        map.put("code", status);
        map.put("message", message);
        map.put("data", null);
        map.put("success", false);
        log.error(map.toString());
        return map;
    }

    /**
     * 获取异常属性
     */
    @Override
    protected Map<String, Object> getErrorAttributes(ServerRequest request, boolean includeStackTrace) {

        int code = HttpStatus.INTERNAL_SERVER_ERROR.value();
        String message = ErrorMsg.SERVER_FAIL;
        Throwable error = super.getError(request);
        if (error == null) {
            response(code, message);
        }
        message = error.getMessage();
        if (error instanceof NotFoundException) {
            code = HttpStatus.NOT_FOUND.value();
        } else if (error instanceof BusinessException) {
            BusinessException bussinessException = (BusinessException) error;
            code = bussinessException.getErrCode();
        } else if (error instanceof TimeoutException) {
            code = HttpStatus.GATEWAY_TIMEOUT.value();
        } else if (error instanceof ExpiredJwtException) {
            code = ErrorCode.TOKEN_EXPIRED;
            message = ErrorMsg.TOKEN_EXPIRED + "：" + error.getMessage();
        }
        return response(code, message);
    }

    /**
     * 指定响应处理方法为JSON处理的方法
     */
    @Override
    protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {
        return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse);
    }

    /**
     * 根据code获取对应的HttpStatus
     */
    @Override
    protected int getHttpStatus(Map<String, Object> errorAttributes) {
        /*int statusCode = (int) errorAttributes.get("code");*/
        return ErrorCode.SUCCESS;
    }
}
